<template>
  <t-space size="small">
    <t-tag
      v-for="(item, idx) in alias"
      :key="item"
      closable
      variant="outline"
      theme="primary"
      @close="handleClose(idx)"
      >{{ item }}</t-tag
    >
    <div>
      <t-tag v-if="!inputVisible" variant="outline" theme="primary" @click="handleClickAdd">
        <template #icon>
          <add-icon />
        </template>
        添加别名
      </t-tag>
      <t-input
        v-else
        ref="input"
        v-model="inputValue"
        size="small"
        style="width: 94px"
        @blur="handleInputEnter"
        @enter="handleInputEnter"
      />
    </div>
  </t-space>
</template>
<script lang="ts" setup>
import { AddIcon } from "tdesign-icons-vue-next";
import MessageUtil from "@/utils/model/MessageUtil";
import MessageBoxUtil from "@/utils/model/MessageBoxUtil";
import { useUrlStore } from "@/store";
import { clientIndexAliasAddApi, clientIndexAliasRemoveApi } from "@/api";

const props = defineProps({
  alias: {
    type: Array as PropType<Array<string>>,
    default: () => []
  },
  size: {
    type: String as PropType<"small" | "medium" | "large">,
    default: "medium"
  },
  index: {
    type: String,
    required: true
  }
});
const emit = defineEmits(["refresh"]);

const inputVisible = ref(false);
const inputValue = ref("");
const input = ref<HTMLInputElement>();

watch(inputVisible, (value) => {
  if (!value) {
    inputValue.value = "";
  }
});

const handleClose = (index: number) => {
  const { id } = useUrlStore();
  if (!id) return MessageUtil.error("请先选择es实例");
  MessageBoxUtil.confirm("此操作将永久删除该别名, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  })
    .then(() =>
      clientIndexAliasRemoveApi(id, props.index, props.alias[index])
        .then((res) => {
          MessageUtil.success(res);
          emit("refresh");
        })
        .catch((e) => MessageUtil.error("删除别名错误", e))
    )
    .catch(() => console.log("取消删除"));
};

const handleInputEnter = () => {
  const { id } = useUrlStore();
  if (!id) return MessageUtil.error("请先选择es实例");
  if (inputValue.value && !props.alias.some((item) => item === inputValue.value)) {
    clientIndexAliasAddApi(id, props.index, inputValue.value)
      .then((res) => {
        // 新增成功
        MessageUtil.success(JSON.stringify(res));
        emit("refresh");
      })
      .catch((e) => MessageUtil.error("新建别名错误", e));
    emit("refresh");
  }
  inputVisible.value = false;
};

const handleClickAdd = () => {
  inputVisible.value = true;
  nextTick(() => {
    input.value?.focus();
  });
};
</script>
<script lang="ts">
/**
 * 索引别名组件
 */
export default {
  name: "IndexAlias"
};
</script>
<style scoped lang="less"></style>
